package top.personal.sglmsn.upload.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import top.personal.sglmsn.upload.dao.FileMd5Dao;
import top.personal.sglmsn.upload.dao.FileUploadDao;
import top.personal.sglmsn.upload.dao.PwdDao;
import top.personal.sglmsn.upload.entity.FileMd5Entity;
import top.personal.sglmsn.upload.entity.FileUploadEntity;
import top.personal.sglmsn.upload.entity.PwdEntity;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;

/**
 * File service
 *
 * @author 王涛
 */
@Service
public class FileService {

    public static final String filePath = "url";
    public static final File parent = new File("");
    @Autowired
    FileMd5Dao fileMd5Dao;
    @Autowired
    FileUploadDao fileUploadDao;

    @Autowired
    PwdDao pwdDao;

    @Transactional
    public FileUploadEntity uploadFile(MultipartFile file, String pwd) {
        FileUploadEntity fileUploadEntity = new FileUploadEntity();
        fileUploadEntity.setUid(IdUtil.objectId());
        fileUploadEntity.setAuthority(1).setCreate_time(new Date()).setUpdate_time(new Date());
        try {
            String s = DigestUtil.md5Hex(file.getInputStream());
            String sha1=DigestUtil.sha256Hex(file.getInputStream());
            FileMd5Entity o = fileMd5Dao.selectOne(new QueryWrapper<FileMd5Entity>(new FileMd5Entity().setMd5(s).setSha1(sha1)));
            fileUploadEntity.setFile_name(file.getOriginalFilename());
            fileUploadEntity.setExtension_name(FileUtil.extName(fileUploadEntity.getFile_name()));
            if (o != null) {
                fileUploadEntity.setFile_md5_id(o.getId());
                fileUploadEntity.setPath(o.getFile_path());
                fileUploadEntity.setUrl(o.getRelative_path());
            } else {
                StringBuilder builder = new StringBuilder(filePath);
                builder.append(File.separator).append(DateUtil.formatDate(new Date()).replaceAll("-", Matcher.quoteReplacement(File.separator)));
                builder.append(File.separator).append(s);
                File file1 = new File(parent.getAbsolutePath(), builder.toString());
                FileUtil.mkParentDirs(file1);
                file.transferTo(file1);
                String url = "/" + builder.toString().replaceAll(Matcher.quoteReplacement(File.separator), "/");
                FileMd5Entity entity = new FileMd5Entity().setMd5(s).setFile_path(file1.getAbsolutePath()).setSha1(sha1).setRelative_path(builder.toString());
                fileMd5Dao.insert(entity);
                fileUploadEntity.setFile_md5_id(entity.getId());
                fileUploadEntity.setPath(entity.getFile_path());
                fileUploadEntity.setUrl(url);
            }

            if (StrUtil.isNotBlank(pwd)) {
                fileUploadEntity.setAuthority(2);
            }
            fileUploadDao.insert(fileUploadEntity);
            if (StrUtil.isNotBlank(pwd)) {
                pwdDao.insert(new PwdEntity().setCreate_time(new Date()).setFile_upload_id(fileUploadEntity.getId()).setPwd(DigestUtil.sha256Hex(pwd)));
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
        }
        return fileUploadEntity;
    }
    public List<FileUploadEntity> uploadFile(MultipartFile[] file, String pwd) {

        List<FileUploadEntity> fileUploadEntities = new LinkedList<>();
        for (MultipartFile multipartFile : file) {
            fileUploadEntities.add(uploadFile(multipartFile,pwd ));
        }
        return fileUploadEntities;
    }

    public FileUploadEntity getFile(String uid) {
        FileUploadEntity fileUploadEntity = fileUploadDao.selectOne(new QueryWrapper<>(new FileUploadEntity().setUid(uid)));
        fileUploadEntity.setFileMd5Entity(fileMd5Dao.selectById(fileUploadEntity.getFile_md5_id()));
        if (Objects.equals(fileUploadEntity.getAuthority(), 2)) {
            PwdEntity pwdEntity = pwdDao.selectOne(new QueryWrapper<>(new PwdEntity().setFile_upload_id(fileUploadEntity.getId())));
            fileUploadEntity.setPwdEntity(pwdEntity);
        }
        return fileUploadEntity;
    }
}
